package service.impl;

import bean.Goods;
import bean.CartItem;
import bean.Page;
import dao.impl.BookDaoImpl;
import service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {

    private BookDaoImpl bookDao= new BookDaoImpl();

    @Override
    public int addBook(Goods goods) {

        return bookDao.addBook(goods);
    }

    @Override
    public int deleteBookById(Integer id) {
        return bookDao.deleteBookById(id);
    }

    @Override
    public int updateBook(Goods goods) {
        return bookDao.updateBook(goods);
    }

    @Override
    public Goods queryById(Integer id) {
        return bookDao.queryById(id);
    }

    @Override
    public List<Goods> queryAllBook() {
        return bookDao.queryAllBook();
    }

    @Override
    public int[] syncStockAndSales(List<CartItem> cartItems) {
        return bookDao.syncStockAndSales(cartItems);
    }

    @Override
    public Page<Goods> pagingQuery(int pageNumber, int pageSize,String classifyName) {

        //获取总数据量
        int pageTotalCount = bookDao.getTotal(classifyName);

        //计算总页数
        int pageTotal;
        if(pageTotalCount%pageSize != 0){
            pageTotal = pageTotalCount / pageSize + 1;
        } else {
            pageTotal = pageTotalCount / pageSize;
        }

        //获取当前页数据
        if(pageNumber < 1){
            pageNumber = 1;
        } else if(pageNumber > pageTotal){
            pageNumber = pageTotal;
        }

        List<Goods> goods = bookDao.pagingQuery((pageNumber - 1) * pageSize, pageSize,classifyName);

        Page<Goods> page = new Page<>(pageNumber, pageTotal, pageSize, pageTotalCount, goods);

        return page;
    }

    @Override
    public Page<Goods> pagingQueryByPrice(int pageNumber, int pageSize, double min, double max) {

        //获取总数据量
        int pageTotalCount = bookDao.getToTalWithPrice(min,max);

        //计算总页数
        int pageTotal;
        if(pageTotalCount%pageSize != 0){
            pageTotal = pageTotalCount / pageSize + 1;
        } else {
            pageTotal = pageTotalCount / pageSize;
        }

        //获取当前页数据
        if(pageNumber < 1){
            pageNumber = 1;
        } else if(pageNumber > pageTotal){
            pageNumber = pageTotal;
        }

        List<Goods> goods = bookDao.pagingQueryByPrice((pageNumber - 1) * pageSize, pageSize,min,max);

        return new Page<>(pageNumber, pageTotal, pageSize, pageTotalCount, goods);

    }

    @Override
    public List<Goods> searchByKeyword(String keyword) {
        try{
            return bookDao.searchByKeyword(keyword);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
